import { createSlice } from "@reduxjs/toolkit"
import { getNotifications, updateNotifcation } from "../actions/notificationAction"
export interface NotificationType {
  id: string
  content: string
  // "datetime": "1692342952",
  // "notification_type": 4,
  read: boolean
  // "updated_by": null,
}

interface NotificationState {
  loading: boolean
  notification: object[]
  error: string
}
const initialState: NotificationState = {
  loading: false,
  notification: [],
  error: "",
}

const notificationSlice = createSlice({
  name: "notifications",
  initialState,
  reducers: {
    setNotificationLoader: (state, action) => {
      const updatedArray = state?.notification?.map((item: any) => {
        if (item.id === action?.payload?.id) {
          return {
            ...item,
            loading: true,
          }
        }
        return item
      })
      //@ts-ignore
      state.notification = updatedArray
    },
    resetNotification: (state) => {
      //@ts-ignore
      state.notification = []
    },
  },
  extraReducers: (builder) => {
    //Reducer to get notifications
    builder
      .addCase(getNotifications.pending, (state, { payload }) => {
        state.loading = true
      })
      .addCase(getNotifications.fulfilled, (state, { payload }) => {
        state.loading = false
        state.error = ""
        state.notification = payload?.result?.map((element) => {
          return {
            ...element,
            loading: false,
          }
        })
        console.log("getNotifications fulfilled")
      })
      .addCase(getNotifications.rejected, (state, { payload }) => {
        state.error = ""
        console.log("rejected in get notifications", payload)
      })

    //Reducer to update notifications
    builder
      .addCase(updateNotifcation.pending, (state, { payload }) => {
        state.loading = true
      })
      .addCase(updateNotifcation.fulfilled, (state, { payload }) => {
        state.loading = false
        console.log("updateNotifcation fulfilled")
      })
      .addCase(updateNotifcation.rejected, (state, { payload }) => {
        state.error = ""
        state.loading = false
        console.log("rejected in get updateNotifcation", payload)
      })
  },
})

export default notificationSlice.reducer
export const { setNotificationLoader, resetNotification } = notificationSlice.actions
